package common; 
import java.sql.*;
import java.io.*;
import java.util.*;

public class Agent_sql_run {

  public static void main(String args[])throws Exception {
    String DB_IP = "";
    String DB_PORT = "";
    String DB_NAME = "";
    String DB_USER = "";
    String DB_PASSWORD = "";
    String ConfigFile = "./dbconfig.db"; 
	
    String RUN_SQL = "";
	
    Connection DBCon= null;
    Statement  stmt = null;
    ResultSet  rs   = null;
	
    String inDate   = new java.text.SimpleDateFormat("yyyyMMdd").format(new java.util.Date());
    String inTime   = new java.text.SimpleDateFormat("HHmmss").format(new java.util.Date());
    
    try {
      Class.forName("com.mysql.jdbc.Driver");
      Properties config = new Properties();
      config.load(new FileInputStream(ConfigFile));
      
      DB_IP       = config.getProperty("DB_IP");
      DB_PORT     = config.getProperty("DB_PORT");
      DB_NAME     = Crypto.DecodeBySType(config.getProperty("DB_NAME"));
      DB_USER     = Crypto.DecodeBySType(config.getProperty("DB_USER"));
      DB_PASSWORD = Crypto.DecodeBySType(config.getProperty("DB_PASSWORD"));
      
      RUN_SQL = args[0];

      DBCon = DriverManager.getConnection("jdbc:mysql://"+ DB_IP +":"+ DB_PORT +"/"+ DB_NAME ,DB_USER,DB_PASSWORD);
      stmt = DBCon.createStatement();
	    
      rs = stmt.executeQuery("call "+ RUN_SQL);

      if (rs != null) {
        ResultSetMetaData rsmd = rs.getMetaData(); 
        int columnCount = rsmd.getColumnCount(); 
        String temp = "[" ;

        while (rs.next()){
          for (int i = 0; i < columnCount; i++){
            temp += rsmd.getColumnName(i+1) +":"+ rs.getString(rsmd.getColumnName(i+1)) +"|";
          }
        }
        temp +="]";
        System.out.println(inDate + inTime +":"+ RUN_SQL+" excuted at =="+ temp );
      } else {
        System.out.println(inDate + inTime +":"+ RUN_SQL+" excuted at == NULL");	    	
      }
    }catch(IOException e)  {	    
      System.out.println(inDate + inTime +":IOException= "+e.getMessage());
    }catch(SQLException e) {
      System.out.println(inDate + inTime +":SQLException= "+e.getMessage());
    }catch(Exception e) {
      System.out.println(inDate + inTime +":Exception= "+e.getMessage());
    }finally {
      try{
        if (rs   != null) rs.close();
        if (stmt != null) stmt.close();
        if (DBCon!= null) DBCon.close();
      }catch(Exception ee){}
    }
  }
}
